#!/usr/bin/env php
<?php
/**
 * Yii console bootstrap file.
 *
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');

function handleFatal()
{
    $error = error_get_last();
    if (isset($error['type'])) {
        switch ($error['type']) {
            case E_ERROR :
            case E_PARSE :
            case E_CORE_ERROR :
            case E_COMPILE_ERROR :
                $message = $error['message'];
                $file = $error['file'];
                $line = $error['line'];
                $log = "$message ($file:$line)\nStack trace:\n";
                $trace = debug_backtrace();
                foreach ($trace as $i => $t) {
                    if (!isset($t['file'])) {
                        $t['file'] = 'unknown';
                    }
                    if (!isset($t['line'])) {
                        $t['line'] = 0;
                    }
                    if (!isset($t['function'])) {
                        $t['function'] = 'unknown';
                    }
                    $log .= "#$i {$t['file']}({$t['line']}): ";
                    if (isset($t['object']) and is_object($t['object'])) {
                        $log .= get_class($t['object']) . '->';
                    }
                    $log .= "{$t['function']}()\n";
                }
                if (isset($_SERVER['REQUEST_URI'])) {
                    $log .= '[QUERY] ' . $_SERVER['REQUEST_URI'];
                }
                error_log($log);
            default:
                break;
        }
    }
}

register_shutdown_function('handleFatal');

require(__DIR__ . '/vendor/autoload.php');
require(__DIR__ . '/vendor/albert/yii2-swoole/Yii.php');
require(__DIR__ . '/common/config/bootstrap.php');
require(__DIR__ . '/console/config/bootstrap.php');
require(__DIR__ . '/common/config/defined.php');

$config = yii\helpers\ArrayHelper::merge(
    require(__DIR__ . '/common/config/main.php'), require(__DIR__ . '/common/config/main-local.php'), require(__DIR__ . '/apistore/config/main.php'), require(__DIR__ . '/apistore/config/main-local.php')
);

new \yii\swoole\Application($config);
global $argv;
array_shift($argv);
$method = array_shift($argv);
$method = substr($method, strpos($method, '/') + 1);
//缓存RPC列表
Yii::$rpcList = Yii::$app->RpcHelper->getRpcClass();
$GLOBALS['call_user_func_array'](['\yii\swoole\commands\SwooleCommand', $method], $argv);

//$config = yii\helpers\ArrayHelper::merge(
//    require(__DIR__ . '/common/config/main.php'), require(__DIR__ . '/common/config/main-local.php'), require(__DIR__ . '/console/config/main.php'), require(__DIR__ . '/console/config/main-local.php')
//);
//
//$application = new \yii\swoole\console\Application($config);
//Yii::$rpcList = Yii::$app->RpcHelper->getRpcClass();
//$exitCode = $application->run();
//exit($exitCode);
